﻿using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;

namespace Simple.Services.System.Jobs
{
    public class TimesTaskService
    {
        private readonly IServiceScopeFactory _scopeFactory;
        private static int _interval;
        private static bool _isRunning = false;
        private static Func<Task> _taskAction;
        private Task _timer;
        private static readonly object _lock = new object();
        public TimesTaskService(IServiceScopeFactory scopeFactory)
        {
            _scopeFactory = scopeFactory;
        }

        public void Initialize(int interval, Func<Task> action)
        {
            _interval = interval;
            _taskAction = action;
        }

        public void Start()
        {
            if (_taskAction == null)
            {
                throw new InvalidOperationException("TimerTaskService is not initialized.");
            }

            lock (_lock)
            {
                if (_isRunning)
                {
                    return;
                }

                _isRunning = true;

                if (_timer == null || _timer.IsCompleted)
                {
                    _timer = Task.Run(async () => await RunTask());
                }
            }
        }

        public void Stop()
        {
            lock (_lock)
            {
                _isRunning = false;
            }
            _timer?.Wait();
            _timer?.Dispose();
            _timer = null;
        }

        private async Task RunTask()
        {
            while (_isRunning)
            {
                await _taskAction();
                await Task.Delay(_interval);
            }
        }
        public async Task<int> UpdateTimesAsync(CancellationToken cancellationToken)
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var _context = scope.ServiceProvider.GetRequiredService<SimpleDbContext>();
                // 确保 _context 已正确初始化
                if (_context == null)
                {
                    throw new InvalidOperationException("Database context is not initialized.");
                }
                using (var transaction = await _context.Database.BeginTransactionAsync(cancellationToken))
                {
                    try
                    {
                        Console.WriteLine("开始转换");

                        // 执行第一个更新语句
                        var rows1 = await _context.Database.ExecuteSqlRawAsync(@"
                    UPDATE QHSE_XY_VIOLATION SET TIMES_VIOLATION = 1 WHERE VIOLATION_CLAUSE IN (
                    SELECT VIOLATION_CLAUSE FROM QHSE_XY_VIOLATION GROUP BY VIOLATION_CLAUSE,VIOLATION_USER_ID HAVING COUNT(*) >= 2)
                    ");

                        Console.WriteLine($"第一条更新语句影响了 {rows1} 行");

                        // 执行第二个更新语句
                        var rows2 = await _context.Database.ExecuteSqlRawAsync(@"
                    UPDATE QHSE_XY_VIOLATION SET TIMES_VIOLATION = 0 WHERE VIOLATION_CLAUSE NOT IN (
                    SELECT VIOLATION_CLAUSE FROM QHSE_XY_VIOLATION GROUP BY VIOLATION_CLAUSE,VIOLATION_USER_ID  HAVING COUNT(*) >= 2
                    )
                    ");

                        Console.WriteLine($"第二条更新语句影响了 {rows2} 行");

                        await transaction.CommitAsync();

                        var totalRows = rows1 + rows2;
                        Console.WriteLine($"总共影响了 {totalRows} 行");
                        return totalRows;
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"发生异常：{ex.Message}");
                        await transaction.RollbackAsync();
                        throw;
                    }
                }
            }

        }
    }





}
